package com.interview.juc;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Account{

    private int money = 1000;
    private Object obj1 = new Object();
    private Object obj2 = new Object();

    //存钱
    public int saveMoney(int m){
        synchronized (obj1){
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            synchronized (obj2){
                money += m;//武功秘籍
            }
        }
        return money;
    }

    //取钱
    public int takeMoney(int m){
        synchronized (obj1){
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            synchronized (obj2){
                money -= m;
            }
        }
        return money;
    }
}

//锁嵌套: 倚天剑  屠龙刀

public class 死锁 {
    public static void main(String[] args) {

        Account account = new Account();

        new Thread( () ->{
            System.out.println(Thread.currentThread().getName() +"开始存钱....");
            int saveMoney = account.saveMoney(1000);
            System.out.println(Thread.currentThread().getName() +"结束存钱...."+saveMoney);
        },"线程A").start();
        //解决方式1
        //try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        // t1.join();
        //解决方式2: 锁对象顺序一致
        new Thread( () ->{
            System.out.println(Thread.currentThread().getName() +"开始取钱....");
            int takeMoney = account.takeMoney(10);
            System.out.println(Thread.currentThread().getName() +"结束取钱...."+takeMoney);
        },"线程B").start();
    }
}
